package org.hot100_6.leetcode2;

import org.algorithm.List.ListNode;
import org.utils.ListNode.ListNodeUtils;

public class Solution {

    public static void main(String[] args) {
        int [] l1 = {9,9,9,9,9,9,9};
        int [] l2 = {9,9,9,9};
        ListNode l1List = ListNodeUtils.createListNode(l1);
        ListNode l2List = ListNodeUtils.createListNode(l2);

        ListNode listNode = addTwoNumbers(l1List, l2List);

        ListNodeUtils.Print(listNode);
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode dummy = new ListNode(-1);

        ListNode temp = dummy;

        int carry = 0;

        while (l1!=null || l2!=null){

            int val1 = 0;
            int val2 = 0;

            if (l1!=null){
                val1 = l1.val;
            }

            if (l2!=null){
                val2 = l2.val;
            }

            int value = carry + val1+ val2;

            carry = value/10;
            ListNode node = new ListNode(value%10);
            temp.next = node;
            temp = temp.next;
            if (l1!=null){
                l1 = l1.next;
            }
            if (l2!=null){
                l2 = l2.next;
            }
        }

        if (carry!=0){
            temp.next = new ListNode(carry);
        }


        return dummy.next;
    }
}
